package net.sky.oa.service.docs.impl;

import java.io.File;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sky.oa.dao.docs.FileAttachDao;
import net.sky.oa.model.FileAttach;
import net.sky.oa.service.docs.DocFileUserService;
import net.sky.oa.service.docs.FileAttachService;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.htsoft.core.service.impl.BaseServiceImpl;
import com.htsoft.core.util.AppUtil;
import com.htsoft.core.web.paging.PagingBean;

@Service
@Transactional
public class FileAttachServiceImpl extends BaseServiceImpl<FileAttach>
  implements FileAttachService
{
  private FileAttachDao dao;
  
  @Autowired
  private DocFileUserService docFileUserService;
  
 /* private DocFileUserDao fileUserDao;  
  
  @Resource
  public void setFileUserDao(DocFileUserDao fileUserDao) {
	super.setDao(fileUserDao);
	this.fileUserDao = fileUserDao;
}
*/
  @Resource
  public void setDao(FileAttachDao dao) {
	  super.setDao(dao);
	  this.dao = dao;
  }
  public List findByParams(int qType,HttpServletRequest request,Long folderId,Long userId,PagingBean pb){
	  String fileId=request.getParameter("Q_id_S_EQ");
	  String createtime=request.getParameter("Q_createtime_D_GE");
	  String fileName=request.getParameter("Q_fileName_S_LK");
	  Long id=StringUtils.isBlank(fileId)?-1:Long.valueOf(fileId);
	  if(qType==5){
		  return docFileUserService.findByParams(id, -1L, -1L, userId, fileName, createtime, pb);
	  }else
	  {
		  return dao.findByParams(qType,folderId,userId,id,fileName,createtime,pb);
	  }
  }
  
  public void removeByPath(String filePath)
  {
    FileAttach fileAttach = this.dao.getByPath(filePath);

    String fullFilePath = AppUtil.getAppAbsolutePath() + "attachFiles/" + filePath;
    fullFilePath=fullFilePath.replace("/", "\\");
    this.logger.info("file:" + fullFilePath);

    File file = new File(fullFilePath);

    if (file.exists()) {
      file.delete();
    }
    if (fileAttach != null)
      this.dao.remove(fileAttach);
  }

  public FileAttach getByPath(String filePath)
  {
    return this.dao.getByPath(filePath);
  }
  
  public void delete(Long id){
	  try{
		  int count=this.dao.findRelation(id);
		  FileAttach entity=new FileAttach();
		  entity=this.get(id);
		  if(count>0)
		  {
			  entity.setStatus(2);
			  this.save(entity);
		  }else
		  {
			  this.removeByPath(entity.getFilePath());
		  }
	  }catch (Exception e) {
		  e.printStackTrace();
	}
  }
  
  
}